﻿#include "datasource.h"
#include <QDomDocument>
#include <QDomElement>
#include <QFile>
#include <QTextStream>

using namespace rxtiler;

rxtiler::DataSource::DataSource()
{

}

DataSource::~DataSource()
{

}

bool DataSource::open()
{
    return false;
}

bool DataSource::close()
{
    return false;
}

Extent DataSource::getExtent()
{
    return Extent();
}

bool DataSource::computerLevels(TileOption *option, int *min, int* max)
{
    return false;
}

osg::Image *DataSource::getImage(TileKey &key,Extent& extent)
{
    return 0;
}

osg::Image *DataSource::getImages(TileKey &key, Extent &extent)
{
     return 0;
}

osg::HeightField *DataSource::getDEM(TileKey &key, Extent &extent)
{
    return 0;
}

bool DataSource::saveImage(TileKey &key, osg::Image *img)
{
    return false;
}

bool DataSource::saveDEM(TileKey &key, osg::HeightField *dem)
{
    return false;
}

void DataSource::setPath(QString p)
{
    this->_path = p;
}

DataSourceMetaData *DataSource::getOrCreateMetaData(){
    if(_metaData == 0){
        _metaData = new DataSourceMetaData();
    }
    return _metaData;
}

//void DataSource::setMetaData(DataSourceMetaData *md){
//    if(!md) return;
//    _metaData = md;
//}

bool DataSource::saveMetaData()
{
    if(!_metaData) return false;
    QString path = this->_path+"/metadata.xml";
    QFile file(path); //相对路径、绝对路径、资源路径都可以
    if (!file.open(QFile::WriteOnly | QFile::Truncate)) //可以用QIODevice，Truncate表示清空原来的内容
    {
        return false;
    }


    QDomDocument doc;
    //添加根节点
    QDomElement root = doc.createElement("data");
    doc.appendChild(root);

    QDomElement lv0 = doc.createElement("level0");
    lv0.appendChild(doc.createTextNode(QString::number(_metaData->level0)));
    root.appendChild(lv0);

    QDomElement lv1 = doc.createElement("level1");
    lv1.appendChild(doc.createTextNode(QString::number(_metaData->level1)));
    root.appendChild(lv1);

    QDomElement left = doc.createElement("left");
    left.appendChild(doc.createTextNode(QString::number(_metaData->dataExtent.left)));
    QDomElement right = doc.createElement("right");
    right.appendChild(doc.createTextNode(QString::number(_metaData->dataExtent.right)));
    QDomElement top = doc.createElement("top");
    top.appendChild(doc.createTextNode(QString::number(_metaData->dataExtent.top)));
    QDomElement bottom = doc.createElement("bottom");
    bottom.appendChild(doc.createTextNode(QString::number(_metaData->dataExtent.bottom)));
    QDomElement extent = doc.createElement("extent");
    extent.appendChild(left);
    extent.appendChild(right);
    extent.appendChild(top);
    extent.appendChild(bottom);
    root.appendChild(extent);



    QTextStream out_stream(&file);
    doc.save(out_stream, 4); //缩进4格
    file.close();
    return true;
}

